#!/usr/bin/perl

#################################################################
#                                                               #
#                     Script: pwsplit.pl                        #
#                     Author: Gary Locke                        #
#                            ~v1~                               #
#    Description: This script should help view only a single    #
#   printing of a command's output as logged by procwatch.sh,   #
#   such as netstat or top, by printing all lines between two   #
#             user-provided time values. Enjoy.                 #
#                                                               #
# Usage: Usage: ./script.pl [log_file] [start_time] [stop_time] #
#                                                               #
#################################################################

sub isMatch {
    $found = `grep $_[0] $searchFile`;
    if (length($found) == 0) {
        print "\nString " . $_[0] . " not found in " . $searchFile . ". Continue anyway? [Y/n]: ";
        chomp($cont = <STDIN>);
        if ($cont =~ /n/) {
            die "\nQuitter.\n";
        }
    }
}

if (defined(@ARGV[0])) {
    $searchFile = @ARGV[0];
} else {
    print "\nCommand line usage:\n\t./script.pl [log_file] [start_time] [stop_time]\n\n";
    print "Enter log file path: ";
    chomp($searchFile = <STDIN>);
}

open(SF, "<", $searchFile);

while(<SF>) {
  chomp;
  push(@searchFile, $_);
}

close(SF);

if (defined(@ARGV[1])) {
    $searchStart = @ARGV[1];
} else {
    print "Enter a start search time (e.g. 18:30): ";
    chomp($searchStart = <STDIN>);
}

$chk = &isMatch($searchStart);

if (defined(@ARGV[2])) {
    $searchStop = @ARGV[2];
} else {
     open(CRON, "<", "/etc/crontab");

    while(<CRON>) {
      chomp;
      push(@cronTab, $_);
    }

    close(CRON);

    foreach (@cronTab) {
        if ("$_" =~ /proc.*watch/) {
            print "\nCurrently scheduled procwatch process: \n" . $_ . "\n\n";
        }
    }

    print "Enter stop search time (e.g. 18:35): ";
    chomp($searchStop = <STDIN>);
}

$chk = &isMatch($searchStop);

print "\n";

$mode = 0;
foreach (@searchFile) {
    if ("$_" =~ /$searchStart/ && "$mode" == 0) {
        $mode++;
    }

    if ("$_" =~ /$searchStop/ && "$mode" > 0) {
        print "\n";
        last;
    }

    if ("$mode" > 0) {
        print "$_\n";
    }
}
